package com.siyu.common.config.aliyun;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.siyu.common.utils.aliyun.service.FileOssStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;



@Configuration
@EnableConfigurationProperties(OssConfigProperties.class)
@ConditionalOnClass(FileOssStorageService.class)
public class OssConfig {

    private final OssConfigProperties ossConfigProperties;

    @Autowired
    public OssConfig(OssConfigProperties ossConfigProperties) {
        this.ossConfigProperties = ossConfigProperties;
    }

    @Bean
    public OSS ossClient() {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(
                ossConfigProperties.getEndpoint(),
                ossConfigProperties.getKeyid(),
                ossConfigProperties.getKeysecret()
        );

        // 创建桶 (bucket)
        String bucketName = ossConfigProperties.getBucketname();
        if (!ossClient.doesBucketExist(bucketName)) {
            ossClient.createBucket(bucketName);
            // 设置桶的权限为公共读
            ossClient.setBucketAcl(bucketName, com.aliyun.oss.model.CannedAccessControlList.PublicRead);
        }

        return ossClient;
    }
}